package com.lalosoft.misgastos.config;

import java.security.MessageDigest;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.lalosoft.misgastos.R;

public class Utils {
	
	public static void showNotification(Context ctx, String ticker, String contentTitle, String contentText, Intent action){
		//show notification
		NotificationManager manager = (NotificationManager)ctx.getSystemService(Context.NOTIFICATION_SERVICE);

		CharSequence tickerText = ticker;
		Notification notification = new Notification(R.drawable.ic_launcher, tickerText, 0);
		
		notification.defaults |= Notification.DEFAULT_SOUND;
//		notification.defaults |= Notification.DEFAULT_VIBRATE;
		notification.flags |= Notification.FLAG_AUTO_CANCEL;
		
		CharSequence contentTitleNotif = contentTitle;
		CharSequence contentTextNotif = contentText;
		if(action == null){
			action = new Intent();
		}
		PendingIntent contentIntent = PendingIntent.getActivity(ctx, 0, action, 0);

		notification.setLatestEventInfo(ctx, contentTitleNotif, contentTextNotif, contentIntent);
		
		manager.notify(1, notification);
	}
	
	public static String checkNetwork(Context ctx){
		String result = null;
	    try {
	        ConnectivityManager cm = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
	        NetworkInfo netInfo = cm.getActiveNetworkInfo();
	        if (netInfo != null && netInfo.isConnected()) {
	        	result = "OK";
	        } else {
	        	result = "No connection";
	        }
	    } catch (Exception e) {
	    	result = "Exception: " + e.getLocalizedMessage();
	    }
	    return result;
	}
	
	public static String getStringFromMD5(String md5) throws Exception{
		MessageDigest md = MessageDigest.getInstance("MD5");
		byte[] digest = md.digest();
		String result = new String(digest);
		return result;
	}
	
	public static String md5(String text) throws Exception{
		MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] md5hash = new byte[32];
        md.update(text.getBytes("iso-8859-1"), 0, text.length());
        md5hash = md.digest();
        return convertToHex(md5hash);
	}
	
	private static String convertToHex(byte[] data) { 
        StringBuffer buf = new StringBuffer();
        for (int i = 0; i < data.length; i++) { 
            int halfbyte = (data[i] >>> 4) & 0x0F;
            int two_halfs = 0;
            do { 
                if ((0 <= halfbyte) && (halfbyte <= 9)) 
                    buf.append((char) ('0' + halfbyte));
                else 
                    buf.append((char) ('a' + (halfbyte - 10)));
                halfbyte = data[i] & 0x0F;
            } while(two_halfs++ < 1);
        } 
        return buf.toString();
    } 
}
